import {AbstractRoom as Room} from "./room/AbstractRoom";
import * as WebSocket from 'ws'
import {EventEmitter} from "events";

export class Client extends EventEmitter {
  id: number;
  sessionId: string;
  private _ws: WebSocket;
  user: { name: string, uid: number };
  room: Room;

  send(type: string, data: any) {
    const msg = {
      data,
      $router: type
    };
    this._ws.send(JSON.stringify(msg));
  }

  set ws(value: WebSocket) {
    this._ws = value;
    this._ws.addEventListener("message", this._onMessage.bind(this));
    this._ws.addEventListener("close", this._onClose.bind(this))
  }

  private _onMessage(event: { data: any; type: string; target: WebSocket }) {
    const res: any = JSON.parse(event.data);
    console.log(event.data)
    this.emit(res.$router, {data: res.data, target: this});
    if (this.room) {
      this.room.onMessage(this, res);
    }
  }

  private _onClose() {
    console.log('close')
    if (this.room) {
      (this.room as any)._leave(this);
    }
  }
}